package bb.lanxing.mvp.view.adapter;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.RecyclerView;

import bb.lanxing.App;
import bb.lanxing.R;
import bb.lanxing.activity.PhotoViewerActivity;
import bb.lanxing.databinding.RouteInfoAdapterItemBinding;
import bb.lanxing.databinding.RouteInfoHeaderBinding;
import bb.lanxing.databinding.sprint.routebook.RouteBookInfoTitleHandle;
import bb.lanxing.databinding.sprint.routebook.RouteInfoCommentHandle;
import bb.lanxing.databinding.sprint.routebook.RouteInfoTitleModel;
import bb.lanxing.manager.SharedManager;
import bb.lanxing.model.database.RouteBook;
import bb.lanxing.model.database.User;
import bb.lanxing.model.json.RouteBookComment;
import bb.lanxing.model.json.TrackSegment;
import bb.lanxing.mvp.presetner.UserProfileUtils;
import bb.lanxing.util.DateUtil;
import bb.lanxing.util.HeaderUtil;
import bb.lanxing.util.MedalUtil;
import bb.lanxing.util.image.GlideUtils;
import bb.lanxing.util.text.NoLineURLSpan;
import bb.lanxing.util.text.TextUtils;
import bb.lanxing.view.UserAvatarView;

public class RouteBookInfoAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private static final int INFO_LIST_TYPE_TITLE = 1;
    private static final int INFO_LIST_TYPE_COMMENT = 2;
    private final List<RouteBookComment> routeBookCommentList = new ArrayList<>();

    private final RouteInfoTitleModel titleModel;
    private RouteInfoCommentHandle commentHandle;
    private RouteInfoHeaderBinding headerBinding;
    private ItemClickListener itemClickListener;
    private RouteBookInfoTitleHandle titleHandle;
    private RouteBook routeBook;
    private Context mContext;
    private boolean showImportLushu = false;

    public RouteBookInfoAdapter(RouteBook routeBook, Context context) {
        this.routeBook = routeBook;
        this.mContext = context;
        this.titleModel = new RouteInfoTitleModel(routeBook, context);
    }

    public void setShowImportLushu(boolean showImportLushu) {
        this.showImportLushu = showImportLushu;
    }

    @Override
    public int getItemViewType(int position) {
        return position == 0 ? INFO_LIST_TYPE_TITLE : INFO_LIST_TYPE_COMMENT;
    }

    public void setCommentHandle(RouteInfoCommentHandle commentHandle) {
        this.commentHandle = commentHandle;
    }

    public void setRouteInfoTitleHandle(RouteBookInfoTitleHandle routeBookInfoTitleHandle) {
        this.titleHandle = routeBookInfoTitleHandle;
    }

    public RouteInfoHeaderBinding getHeaderBinding() {
        return this.headerBinding;
    }

    public RouteBookComment getItem(int position) {
        return this.routeBookCommentList.get(position - 1);
    }

    public void setItemClickListener(ItemClickListener itemClickListener) {
        this.itemClickListener = itemClickListener;
    }

    public void insertComment(int location, RouteBookComment obj) {
        this.routeBookCommentList.add(location, obj);
        notifyDataSetChanged();
    }

    public boolean delete(RouteBookComment obj) {
        boolean remove = this.routeBookCommentList.remove(obj);
        if (remove) {
            notifyDataSetChanged();
        }
        return remove;
    }

    public void updateCommentData(List<RouteBookComment> routeBookCommentList, boolean needClean) {
        if (needClean) {
            getItemCount();
            this.routeBookCommentList.clear();
            notifyDataSetChanged();
        }
        getItemCount();
        this.routeBookCommentList.addAll(routeBookCommentList);
        if (routeBookCommentList.isEmpty()) {
            return;
        }
        notifyDataSetChanged();
    }

    public void updateTitleData(RouteBook routeBook) {
        this.routeBook = routeBook;
        this.titleModel.updateData(routeBook);
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        parent.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
        LayoutInflater from = LayoutInflater.from(parent.getContext());
        if (viewType == INFO_LIST_TYPE_TITLE) {
            this.headerBinding = DataBindingUtil.inflate(from, R.layout.route_info_header, parent, false);
            return new RouteInfoTitleHolder(this.headerBinding);
        }
        return new RouteCommentHolder(DataBindingUtil.inflate(from, R.layout.route_info_adapter_item, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder holder, int position) {
        ImageView imageView;
        boolean z;
        ImageView imageView2;
        boolean z2;
        Drawable drawable;
        String str;
        if (this.routeBook == null) {
            return;
        }
        int i = 0;
        if (holder instanceof RouteCommentHolder routeCommentHolder) {
            RouteInfoAdapterItemBinding itemBinding = routeCommentHolder.getItemBinding();
            int i2 = position - 1;
            LinearLayout linearLayout = itemBinding.getRoot().findViewById(R.id.medal_container_layout);
            RouteBookComment routeBookComment = this.routeBookCommentList.get(i2);
            itemBinding.photoView.setAvatarMode(UserAvatarView.AVATAR_SIZE_36);
            itemBinding.photoView.setAvatarForUrl(routeBookComment.getUserPic());
            itemBinding.photoView.setUserLevelText(routeBookComment.getLevel());
            if (routeBookComment.getProName() != null && !routeBookComment.getProName().isEmpty()) {
                itemBinding.photoView.setProTitle(routeBookComment.getProName());
                itemBinding.photoView.isShowAvatarFrame(true);
                imageView = null;
                z = true;
            } else {
                imageView = null;
                itemBinding.photoView.setProTitle(null);
                itemBinding.photoView.isShowAvatarFrame(false);
                z = false;
            }
            itemBinding.photoView.goToUserInfo(routeBookComment.getUserId());
            MedalUtil.showAvatarMedal(routeBookComment.getMedalSmall(), linearLayout, routeBookComment.getPlateNum(), z,
                    this.mContext, routeBookComment.getUserAvatarMedals(), routeBookComment.getLicenseNumberSkin(),
                    routeBookComment.getLicenseNumberColor());
            itemBinding.lushuCommentReply.setOnClickListener(v -> {
                if (null != commentHandle) {
                    commentHandle.onCommentReplyClick(position);
                }
            });
            boolean z3 = routeBookComment.getTime() == -1 || routeBookComment.getTime() == -2;
            String imageUrl = routeBookComment.getImageUrl();
            if (!android.text.TextUtils.isEmpty(imageUrl)) {
                final String[] split = imageUrl.split(";");
                itemBinding.listphoto1.setVisibility(split.length >= 1 ? View.VISIBLE : View.GONE);
                itemBinding.listphoto2.setVisibility(split.length >= 2 ? View.VISIBLE : View.GONE);
                itemBinding.listphoto3.setVisibility(split.length >= 3 ? View.VISIBLE : View.GONE);
                while (i < split.length) {
                    if (i == 0) {
                        imageView2 = itemBinding.listphoto1;
                    } else if (i == 1) {
                        imageView2 = itemBinding.listphoto2;
                    } else {
                        imageView2 = i == 2 ? itemBinding.listphoto3 : imageView;
                    }
                    if (i <= 2) {
                        GlideUtils.companion.loadImage(imageView2.getContext(),
                                GlideUtils.companion.appendImagePath(split[i], z3 ? 8 : 12), imageView2,
                                R.drawable.ic_default, R.drawable.ic_default);
                        int finalI = i;
                        imageView2.setOnClickListener(view -> {
                            Intent intent = new Intent(RouteBookInfoAdapter.this.mContext, PhotoViewerActivity.class);
                            intent.putExtra("cur_index", finalI);
                            intent.putExtra("photo_url_array", split);
                            RouteBookInfoAdapter.this.mContext.startActivity(intent);
                        });
                    }
                    i++;
                }
            } else {
                itemBinding.listphoto1.setVisibility(View.GONE);
                itemBinding.listphoto2.setVisibility(View.GONE);
                itemBinding.listphoto3.setVisibility(View.GONE);
            }
            itemBinding.createTimeView.setText(getCreateTime(routeBookComment));
            itemBinding.contentView.setText(getCommentContent(routeBookComment));
            itemBinding.nameView.setText(routeBookComment.getUserName());
            holder.itemView.setOnLongClickListener(view -> {
                if (RouteBookInfoAdapter.this.itemClickListener != null) {
                    RouteBookInfoAdapter.this.itemClickListener.OnItemLongClickListener(holder.getAdapterPosition());
                    return true;
                }
                return true;
            });
        } else {
            RouteInfoHeaderBinding headerBinding = ((RouteInfoTitleHolder) holder).getHeaderBinding();
            headerBinding.setRouteInfo(this.titleModel);
            RouteBookInfoTitleHandle routeBookInfoTitleHandle = this.titleHandle;
            if (routeBookInfoTitleHandle != null) {
                headerBinding.setHandle(routeBookInfoTitleHandle);
            }
            headerBinding.setRouteBook(this.routeBook);
            GlideUtils.companion.loadImage(headerBinding.mapView.getContext(),
                    GlideUtils.companion.appendImagePath(this.titleModel.getMapViewImageUrl(), 8),
                    headerBinding.mapView, R.drawable.bg_summary_default_map, R.drawable.bg_summary_default_map);
            LinearLayout linearLayout2 = headerBinding.getRoot().findViewById(R.id.medal_container_layout);
            GlideUtils.companion.loadImage(headerBinding.altitudeImage.getContext(),
                    this.titleModel.getMapAltitudeViewUrl(), headerBinding.altitudeImage,
                    R.drawable.bg_summary_default_map, R.drawable.bg_summary_default_map);
            headerBinding.routeUserphoto.setAvatarMode(UserAvatarView.AVATAR_SIZE_36);
            headerBinding.routeUserphoto.setAvatarForUrl(this.routeBook.getUserAvatar());
            headerBinding.routeUsername.setText(routeBook.getUsername());
            String format = DateUtil.format(routeBook.getCreateTime());
            headerBinding.routeCreateTime.setText(format);
            if (this.routeBook.getProName() != null && !this.routeBook.getProName().isEmpty()) {
                headerBinding.routeUserphoto.setProTitle(this.routeBook.getProName());
                headerBinding.routeUserphoto.isShowAvatarFrame(true);
                z2 = true;
            } else {
                headerBinding.routeUserphoto.setProTitle(null);
                headerBinding.routeUserphoto.isShowAvatarFrame(false);
                z2 = false;
            }
            if (this.routeBook.getUserId() == SharedManager.getInstance().getUserId()) {
                User signinUser = App.getContext().getSigninUser();
                if (signinUser == null) {
                    headerBinding.routeUserphoto.setUserLevelText(this.routeBook.getLevel());
                    MedalUtil.showAvatarMedal(this.routeBook.getMedalSmall(), linearLayout2,
                            this.routeBook.getPlateNum(), z2, this.mContext, this.routeBook.getUserAvatarMedals(),
                            this.routeBook.getLicenseNumberSkin(), this.routeBook.getLicenseNumberColor());
                } else {
                    headerBinding.routeUserphoto.setUserLevelText(signinUser.getLevel());
                }
            } else {
                headerBinding.routeUserphoto.setUserLevelText(this.routeBook.getLevel());
                headerBinding.routeUserphoto.goToUserInfo(this.routeBook.getUserId());
                MedalUtil.showAvatarMedal(this.routeBook.getMedalSmall(), linearLayout2, this.routeBook.getPlateNum(),
                        z2, this.mContext, this.routeBook.getUserAvatarMedals(), this.routeBook.getLicenseNumberSkin(),
                        this.routeBook.getLicenseNumberColor());
            }
            headerBinding.routeDescriptionMore.setTag(false);
            if (this.routeBook.getTrackSegment() != null) {
                TrackSegment trackSegment = this.routeBook.getTrackSegment();
                headerBinding.routeSegmentTopUserPhoto.setAvatarMode(UserAvatarView.AVATAR_SIZE_36);
                headerBinding.routeSegmentTopUserPhoto.setAvatarForUrl(trackSegment.getUserAvatar());
                headerBinding.routeSegmentTopUserPhoto.setUserLevelText(trackSegment.getLevel());
                MedalUtil.showAvatarMedal(trackSegment.getMedalSmall(), trackSegment.getPlateNum(),
                        headerBinding.championPlateNumber, headerBinding.addMedalShowOneChampion,
                        headerBinding.addMedalShowTwoChampion, headerBinding.addMedalShowThreeChampion);
                if (trackSegment.getProName() != null && !trackSegment.getProName().isEmpty()) {
                    headerBinding.routeSegmentTopUserPhoto.isShowAvatarFrame(true);
                    headerBinding.routeSegmentTopUserPhoto.setProTitle(trackSegment.getProName());
                } else {
                    headerBinding.routeSegmentTopUserPhoto.isShowAvatarFrame(false);
                    headerBinding.routeSegmentTopUserPhoto.setProTitle(null);
                }
                HeaderUtil.INSTANCE.setHeader(headerBinding.routeSegmentTopUserPhoto, mContext.getContentResolver());
            }
            headerBinding.lushuNumber.setOnLongClickListener(v -> {
                boolean copyTextToClipBoard = TextUtils.copyTextToClipBoard(v.getContext(),
                        RouteBookInfoAdapter.this.routeBook != null
                                ? String.valueOf(RouteBookInfoAdapter.this.routeBook.getServerId())
                                : "");
                if (copyTextToClipBoard) {
                    App.getContext().showMessage(R.string.toast_copy_success);
                }
                return copyTextToClipBoard;
            });
        }
    }

    @Override
    public int getItemCount() {
        return 1 + this.routeBookCommentList.size();
    }

    private String getCreateTime(RouteBookComment comment) {
        if (comment.getTime() == -1) {
            return this.mContext.getString(R.string.post_queue_sending);
        }
        if (comment.getTime() == -2) {
            return this.mContext.getString(R.string.post_queue_send_failed);
        }
        return DateUtil.format(comment.getTime(), 0);

    }

    private String getCommentContent(RouteBookComment comment) {
        NoLineURLSpan noLineURLSpan;
        String str;
        int length;
        long userId = ((App) ((Activity) this.mContext).getApplication()).getUserId();
        int color = this.mContext.getResources().getColor(R.color.topic_text_red_color);
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(comment.getContent());
        if (comment.getInformedUserId() > 0) {
            String buildUserViewURL = UserProfileUtils.buildUserViewURL(comment.getUserId());
            int color2 = this.mContext.getResources().getColor(R.color.global_blue_color);
            if (userId == comment.getInformedUserId()) {
                noLineURLSpan = new NoLineURLSpan(buildUserViewURL, color);
                String str2 = this.mContext.getString(R.string.topic_post_me) + " ";
                str = this.mContext.getString(R.string.topic_post_reply_to, str2);
                length = str.length() - str2.length();
            } else {
                noLineURLSpan = new NoLineURLSpan(buildUserViewURL, color2);
                String informedUserName = comment.getInformedUserName();
                if (informedUserName == null) {
                    informedUserName = "";
                }
                str = this.mContext.getString(R.string.topic_post_reply_to, informedUserName) + " ";
                length = (str.length() - informedUserName.length()) - 1;
            }
            noLineURLSpan.updateDrawState(new TextPaint());
            spannableStringBuilder.insert(0, (CharSequence) str);
            spannableStringBuilder.setSpan(noLineURLSpan, length, str.length(), 34);
        }
        return spannableStringBuilder.toString();
    }

    public interface ItemClickListener {
        void OnItemLongClickListener(int position);
    }

    private static class RouteCommentHolder extends RecyclerView.ViewHolder {
        private final RouteInfoAdapterItemBinding itemBinding;

        private RouteCommentHolder(RouteInfoAdapterItemBinding binding) {
            super(binding.getRoot());
            this.itemBinding = binding;
        }

        public RouteInfoAdapterItemBinding getItemBinding() {
            return this.itemBinding;
        }
    }

    private static class RouteInfoTitleHolder extends RecyclerView.ViewHolder {
        private final RouteInfoHeaderBinding headerBinding;

        private RouteInfoTitleHolder(RouteInfoHeaderBinding binding) {
            super(binding.getRoot());
            this.headerBinding = binding;
        }

        public RouteInfoHeaderBinding getHeaderBinding() {
            return this.headerBinding;
        }
    }
}
